/**
 * Copyright 2011 Steffen Kaempke
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.pennychecker.eventbus.example.controller;

import java.util.ArrayList;
import java.util.List;

import com.pennychecker.eventbus.HandlerManager;
import com.pennychecker.eventbus.example.event.EditUserEvent;
import com.pennychecker.eventbus.example.event.UserAddedEvent;
import com.pennychecker.eventbus.example.event.UserAddedEventHandler;
import com.pennychecker.eventbus.example.event.UserChangedEvent;
import com.pennychecker.eventbus.example.event.UserChangedEventHandler;
import com.pennychecker.eventbus.example.model.User;

/**
 * There is a control class. In this class, the logic 
 * is encapsulated in order to display all users, 
 * create a new or an existing one to edit.
 * 
 * @author Steffen Kaempke mailto:sk@pennychecker.com
 * 
 */
public final class AllUserController {
	private final List<User> users = new ArrayList<User>();
	private final HandlerManager eventBus;

	/**
	 * Each controller class requires an instance of the 
	 * EventBus. This is achieved by dependency injection.
	 * 
	 * @param eventBus
	 */
	public AllUserController(HandlerManager eventBus) {
		assert null != eventBus;
		this.eventBus = eventBus;
		registerListener();
	}

	/**
	 * Registered events, which should be listened to.
	 */
	private void registerListener() {

		eventBus.addHandler(UserChangedEvent.TYPE, new UserChangedEventHandler() {

			/**
			 * If a user's data have been changed, then this 
			 * listener is invoked.
			 */
			public void onUserChangedEvent(UserChangedEvent event) {
				final User user = event.getUser();
				if (null == user) {
					return;
				}
			
				renderUser(user);
			}
		});

		/**
		 * When a new user is created, then this 
	     * listener is invoked.
		 */
		eventBus.addHandler(UserAddedEvent.TYPE, new UserAddedEventHandler() {

			public void onUserAddedEvent(UserAddedEvent event) {
				final User user = event.getUser();
				assert null != user;
				users.add(user);
				renderUser(user);
				
				/**
				 * Here is just the press of a button simulates.
				 */
				eventBus.fireEvent(new EditUserEvent(user));
			}
		});
	}

	/**
	 * Takes a user's data to display.
	 * 
	 * @param user
	 */
	private void renderUser(User user) {
		System.out.println("User: " + user.getFirstname() + " " + user.getLastname() + ".");
	}
}
